import { defineStore, acceptHMRUpdate } from 'pinia'
import router, { constantRoutes } from '@/router'
import { transformRoutes } from '@/utils/router'
import { useUserStore } from '@/store'
import { getUserBaseData } from '@/api/system/user'
import type { RouteRecordRaw } from 'vue-router'

export const usePermissionStore = defineStore('permission', () => {
  /** 所有路由，包括静态和动态路由 */
  const routes = ref<RouteRecordRaw[]>([])
  const isRoutesLoaded = ref(false)

  /**
   * 生成动态路由
   */
  function generateRoutes() {
    const user = useUserStore()
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      getUserBaseData()
        .then(data => {
          user.updateUserInfo(data.result)
          const dynamicRoutes = transformRoutes(data.result.menuList)
          routes.value = constantRoutes.concat(dynamicRoutes)
          isRoutesLoaded.value = true
          resolve(dynamicRoutes)
        })
        .catch(error => {
          reject(error)
        })
    })
  }

  /**
   * 重置路由
   */
  const resetRouter = () => {
    // 删除动态路由，保留静态路由
    routes.value.forEach(route => {
      if (route.name && !constantRoutes.find(r => r.name === route.name)) {
        router.removeRoute(route.name) // 从 router 实例中移除动态路由
      }
    })

    routes.value = []
    isRoutesLoaded.value = false
  }

  return {
    routes,
    isRoutesLoaded,
    generateRoutes,
    resetRouter
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(usePermissionStore, import.meta.hot))
}
